package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// main
//
//	@Description: 响应数据的学习！！ string json xml jsonp html
func main() {

	engine := gin.Default()
	//设置自定义模板函数

	//加载模板文件(返回为html时) 配置html模板的路径
	engine.LoadHTMLGlob("templates/demo02/*")

	// 返回值为string
	engine.GET("/string", func(c *gin.Context) {
		c.String(http.StatusOK, "%s", "hello")
	})

	//返回值为json	gin.H 本质是map[string]any
	engine.GET("/json", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"success": true,
			"msg":     "hello-json",
			"code":    200,
		})
	})
	//返回值为json	返回 map[string]interface{}
	engine.GET("/json1", func(c *gin.Context) {
		c.JSON(http.StatusOK, map[string]interface{}{
			"success": true,
			"msg":     "hello-json1",
			"code":    200,
		})
	})

	//返回值为json	返回结构体，会自动将结构体转换成map[string]any
	engine.GET("/json2", func(c *gin.Context) {
		c.JSON(http.StatusOK,
			//返回的key是小写，因为 `json:"name"`
			&Student{
				Name: "小明",
				Age:  18,
				Addr: "北京",
			},
		)
	})

	//返回值为json	返回切片
	engine.GET("/json3", func(c *gin.Context) {
		c.JSON(http.StatusOK,
			getStudentList(),
		)
	})

	//jsonp ,可以传递callback
	//不加参数(和返回json一样): http://localhost:8888/jsonp  返回  {"code":200,"msg":"hello-jsonp","success":true}
	//如果后面添加参数： http://localhost:8888/jsonp?callback=xxx  返回 xxx({"code":200,"msg":"hello-jsonp","success":true});
	engine.GET("/jsonp", func(c *gin.Context) {
		c.JSONP(http.StatusOK, map[string]interface{}{
			"success": true,
			"msg":     "hello-jsonp",
			"code":    200,
		})
	})

	//返回xml 将结构体转换成xml：
	//<Student>
	//<Name>小明</Name>
	//<Age>18</Age>
	//<Addr>北京</Addr>
	//</Student>
	engine.GET("/xml", func(c *gin.Context) {
		c.XML(http.StatusOK, &Student{
			Name: "小明",
			Age:  18,
			Addr: "北京",
		})
	})

	//返回xml
	//<map>
	//<success>true</success>
	//<msg>hello-xml</msg>
	//<code>200</code>
	//</map>
	engine.GET("/xml1", func(c *gin.Context) {
		c.XML(http.StatusOK, gin.H{
			"success": true,
			"msg":     "hello-xml",
			"code":    200,
		})
	})

	//返回模板的html
	engine.GET("/html", func(c *gin.Context) {
		c.HTML(http.StatusOK,
			"demo02/index.html", //在对应的html标记上名称，此处使用该名称,需要对应上
			gin.H{
				"time": time.Now().Format("2006-01-02 15:04:05"), //传入到对应的html页面 {{ .time }}
				"week": time.Now().Weekday().String(),
			},
		)
	})

	//返回模板的html
	engine.GET("/html1", func(c *gin.Context) {
		c.HTML(http.StatusOK,
			"demo02/news.html", //在对应的html标记上名称，此处使用该名称,需要对应上
			gin.H{
				"title":   "这是新闻页面",
				"content": "这是新闻内容",
			},
		)
	})

	err := engine.Run(":8881")
	if err != nil {
		return
	}
}

type Student struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
	Addr string `json:"addr"`
}

func getStudentList() []*Student {
	return []*Student{
		{
			Name: "tom",
			Age:  22,
			Addr: "北京",
		},
		{
			Name: "jack",
			Age:  18,
			Addr: "上海",
		},
	}
}
